package com.tchepannou.limbe.validation;

import javax.validation.constraints.Size;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;

/**
 * User: herve
 * Date: 14-01-12 12:33 PM
 */
public class SizeValidator extends AbstractValidator
{
    @Override
    public boolean validate(Object bean, Field field)
    {
        Size anno = field.getAnnotation(Size.class);
        if (anno == null)
        {
            return false;
        }

        int size;
        int min = anno.min();
        int max = anno.max();
        Object value = getValue(bean, field);

        if (value instanceof String)
        {
            size = ((String)value).length();
        }
        else if (value instanceof Collection)
        {
            size = ((Collection)value).size();
        }
        else if (value instanceof Map)
        {
            size = ((Map)value).size();
        }
        else if (value instanceof Array)
        {
            size = Array.getLength(value);
        }
        else
        {
            return false;
        }

        return size>=min && size<=max;
    }

    @Override
    public boolean validate(Object bean)
    {
        return false;
    }
}
